
<template>
    <div style="height:100%">
      
        
  
      <!-- 账单 -->
      <div class="marbot12" v-if="!isObjectEmpty(props.yuguItem)">
        <div class="card">
          
          <div class="flex marbot8">
            <div class="flex_1 marr12">
              <div class="marbot2" style="color:rgba(0, 0, 0, 0.6);line-height:20px">创建时间</div>
              <div  style="color:rgba(0, 0, 0, 1);line-height:20px">{{props.yuguItem.created_at}}</div>
            </div>
            <div class="flex_1">
              <div class="marbot2" style="color:rgba(0, 0, 0, 0.6);line-height:20px">账单金额</div>
              <div style="color:rgba(0, 0, 0, 1);line-height:20px">{{props.yuguItem.pay_price}}</div>
            </div>
          </div>
          <div style="font-size:14px;line-height:24px">预估账单是在创建提货单时，按提单所有货物下单当天能全部装车提走生成的预估账单，该账单仅作费用参考</div>
  
        </div>
      </div>
      <div class='flex flex_wrap' v-if="props.list.length != 0">
              <div class="cards" v-for="(item,index) in props.list" :key="index">
          <div class="flex justify_between align_center marbot8">
            <!-- @click="item.disabled?'':handlePiLiang(index)" -->
            <div class="flex align_center cursor" >
              <!-- <div class="marr12">
                <div class="flex align_center justify_center" style="width:16px;height:16px;border-radius:2px;border:1px solid rgba(0,0,0,.15);background:rgba(0,0,0,.15)" v-if="item.disabled"></div>
                <div class="flex align_center justify_center " style="width:16px;height:16px;border-radius:2px;border:1px solid rgba(0,0,0,.15)" v-if="!item.disabled && !item.flag"></div>
                <div class="flex align_center justify_center" style="width:16px;height:16px;border-radius:2px;border:1px solid rgba(31, 108, 235, 1);background:rgba(31, 108, 235, 1);" v-if="!item.disabled && item.flag">
                  <icon-check style="color:#fff" />
                </div>
              </div> -->
              <div style="font-size:16px;line-height:24px;font-weight:600">账单号：{{item.order_number}}</div>
            </div>
            <div class="flex">
              <!-- <div class="butNt cursor" style="margin-right: 16px;" @click="handleShouJu(item)">收据</div> -->
              <a-popover title="账单明细" trigger="click" position="left">
                <div class="butNt cursor">账单明细</div>
                  <template #content>
                    <div style='width:1000px'>
                      <a-table :columns="tablecolumnsts" :bordered="{ wrapper: true, cell: true }" :data="item.detail" :span-method="spanMethodAll" :pagination="false" :scroll="{y:700}"></a-table>
                    </div>
                </template>
              </a-popover>
            </div>
          </div>
          <div class="flex justify_between marbot12">
            <div class="flex_1">
              <div class="marbot2" style="color:rgba(0, 0, 0, 0.6);line-height:20px">结算状态</div>
              <div  style="color:rgba(0, 0, 0, 1);line-height:20px;font-size:14px;">{{item.is_jiesuan == 1?'已结算':'未结算'}}</div>
            </div>
            <!-- <div class="flex_1">
              <div class="marbot2" style="color:rgba(0, 0, 0, 0.6);line-height:20px">支付方式</div>
              <div  style="color:rgba(0, 0, 0, 1);line-height:20px;font-size:14px;">{{item.pay_type == 'now_pay'?'现结':item.pay_type == 'periodic'?'周期结算':item.pay_type == 'money'?'预付款':'-'}}</div>
            </div> -->
            
            <div class="flex_1">
              <div class="marbot2" style="color:rgba(0, 0, 0, 0.6);line-height:20px">不含税金额</div>
              <div  style="color:rgba(0, 0, 0, 1);line-height:20px;font-size:14px;">{{item.no_tax_price}}</div>
            </div>
            <div class="flex_1">
              <div class="marbot2" style="color:rgba(0, 0, 0, 0.6);line-height:20px">税额</div>
              <div  style="color:rgba(0, 0, 0, 1);line-height:20px;font-size:14px;">{{item.tax_price}}</div>
            </div>
            
          </div>
          <div class="flex justify_between marbot12">
            <!-- <div class="flex_1">
              <div class="marbot2" style="color:rgba(0, 0, 0, 0.6);line-height:20px">线上支付方式</div>
              <div  style="color:rgba(0, 0, 0, 1);line-height:20px;font-size:14px;">{{item.now_pay_type == 1?'惠支付':item.now_pay_type == 2?'支付宝':item.now_pay_type == 3?'对公转账':'-'}}</div>
            </div> -->
            <div class="flex_1">
              <div class="marbot2" style="color:rgba(0, 0, 0, 0.6);line-height:20px">实际支付金额</div>
              <div  style="color:rgba(0, 0, 0, 1);line-height:20px;font-size:14px;">{{item.pay_real_price}}</div>
            </div>
            <div class="flex_1">
              <div class="marbot2" style="color:rgba(0, 0, 0, 0.6);line-height:20px">创建时间</div>
              <div  style="color:rgba(0, 0, 0, 1);line-height:20px;font-size:14px;">{{item.created_at}}</div>
            </div>
            <div class="" style="width: 33.333%;">
              <div class="marbot2" style="color:rgba(0, 0, 0, 0.6);line-height:20px">支付时间</div>
              <div  style="color:rgba(0, 0, 0, 1);line-height:20px;font-size:14px;">{{item.pay_date || '-'}}</div>
            </div>
          </div>
          <div class="flex justify_between">
            <div class="flex_1">
              <div class="marbot2" style="color:rgba(0, 0, 0, 0.6);line-height:20px;margin-right:4px">备注：</div>
              <div  style="color:rgba(0, 0, 0, 1);line-height:20px;font-size:14px;">{{item.remark || '-'}}</div>
            </div>
            
          </div>
        </div>
          </div>
          <div class="flex justify_center align_center" style="height:100%;width:100%" v-if="props.list.length == 0 && isObjectEmpty(props.yuguItem)">
              <a-empty />
          </div>
  
      <a-modal :mask-closable="false"  v-model:visible="editVisible">
  
      </a-modal>
      <ma-form-modal
          v-if='showEdit'
          :width="800"
          title="账单编辑"
          ref="editRef"
          :pay_type='1'
          :submit="editSubmit"
          :columns="editColumn"
      >
  
      </ma-form-modal>
  
      <ma-form-modal
          :width="800"
          title="退款申请"
          ref="refundRef"
          :submit="refundSubmit"
          :columns="[
              {
                dataIndex: 'pay_price',
                title: '金额',
                formType: 'input-number',
                rules: {
                  required: true,
                  message: '请输入金额'
                }
              },
              {
                dataIndex: 'pay_price_item',
                title: '退款项目',
                formType: 'input',
                rules: {
                  required: true,
                  message: '请输入退款项目'
                }
              },
              {
                dataIndex: 'remark',
                title: '退款备注',
                formType: 'textarea',
                rules: {
                  required: true,
                  message: '请输入退款备注'
                }
              },
          ]"
      >
  
      </ma-form-modal>
      <a-modal :mask-closable="false"  v-model:visible="showModal" title="退费申请" @cancel="handleQuxiao" :width="800" ok-text='确定' :on-before-ok="handelOk">
        
        <a-table row-key="id" :columns="tablecolumns" :data="itemDetail?.detail" :row-selection="{type: 'checkbox',showCheckedAll: true,onlyCurrent: false,}"
               v-model:selectedKeys="selectedKeys" :pagination="false" @selection-change="handleSelChange" style="margin-bottom: 2%;">
        </a-table>
        <div style="display: flex;align-items: center;margin-bottom: 2%;">
          <div style="width: 80px;">退款金额</div>
          <a-input :style="{width:'320px'}" v-model="pay_price" placeholder="请输入金额" allow-clear />
        </div>
        <div style="display: flex;align-items: center;margin-bottom: 2%;">
          <div style="width: 80px;">退款项目</div>
          <a-input :style="{width:'320px'}" v-model="pay_price_item" placeholder="请输入退款项目" allow-clear />
        </div>
        <div style="display: flex;">
          <div style="width: 80px;">退款备注</div>
          <a-textarea placeholder="请输入退款备注" v-model="remark" allow-clear style="flex: 1;"/>
        </div>
      </a-modal>
      <a-modal :mask-closable="false"  v-model:visible="props.zhifuShow" title="批量支付" @cancel="handlezhifuQuxiao" :width="800" ok-text='确定' @ok="handelzhifuOk">
        <div style="display: flex;align-items: center;margin-bottom: 2%;">
          <div style="width: 80px;">结算方式</div>
          <a-radio-group v-model="jiesuan" :options="jiesuanOptions" />
        </div>
        <div v-if='jiesuan == 3'>
          <div style="display: flex;align-items: center;margin-bottom: 2%;">
            <div style="width: 80px;">支付方式</div>
            <a-radio-group v-model="zhifu" :options="zhifuOptions" />
          </div>
          <div style="display: flex;align-items: center;margin-bottom: 2%;">
            <div style="width: 80px;">开户行</div>
            <div >{{opening_bank}}</div>
          </div>
          <div style="display: flex;align-items: center;margin-bottom: 2%;">
            <div style="width: 80px;">收款账户</div>
            <div >{{account}}</div>
          </div>
          <div style="display: flex;align-items: center;margin-bottom: 2%;">
            <div style="width: 80px;">开户名称</div>
            <div >{{account_name}}</div>
          </div>
          <div style="display: flex;margin-bottom: 2%;">
            <div style="width: 80px;">上传凭证</div>
            <ma-upload v-model="fileList" returnType='url' />
          </div>
        </div>
      </a-modal>
  
      <!-- 打印派送单 -->
          <a-modal :mask-closable="false" 
              v-model:visible="shoujuShow"
              width="auto"
              title="打印收据"
              ok-text="打印"
              :footer="false"
          >
              <shouju :user="user" :row="shoujuItem"  v-if="shoujuShow"></shouju>
          </a-modal>
    </div>
  </template>
  
  <script setup>
  import {ref, shallowRef,reactive,computed,onMounted,defineProps, defineEmits } from "vue";
  import FinancialPayOrder from "@/api/financial/financialPayOrder";
  import PriceConfigEditCompanies from "@/views/system/userContractCharging/PriceConfigEdit.vue";
  import MaFormModal from "@/components/ma-form-modal/index.vue"
  import shouju from "@/components/shoukuan/index.vue"
  import { useUserStore } from "@/store";
  import { request } from "@/utils/request.js";
  import {cloneDeep, get, isEmpty} from "lodash";
  import {Message} from "@arco-design/web-vue";
  import tool from '@/utils/tool'
  import dept from "@/api/system/dept";
  const emit = defineEmits(["shuaxin","zhifushows","chuanList"]);
  const userStore = useUserStore();
      // 当前登录的用户所有信息，包括 id 用户名 昵称 等信息
  const user = userStore.user;
  const props = defineProps({
      list:{
          type: Array,
          default:[],
      },
      yuguItem:{
          type: Object,
          default:{},
      },
      zhifuShow:{
        type:Boolean,
        default:false,
      }
  })
  const shoujuShow = ref(false)
  const shoujuItem = ref({})
  const env = ref(import.meta.env);
  const token = ref(tool.local.get(import.meta.env.VITE_APP_TOKEN_PREFIX));
  const crudRef = ref()
  const visible = ref(false)
  const editVisible = ref(false)
  const editPayItem = ref({})
  const editRef = ref({})
  const data = ref([])
  const refundRef = ref()
  const showModal = ref(false)
  const pay_price = ref('')
  const pay_price_item = ref('')
  const remark = ref('')
  const itemDetail = ref()
  const selectedKeys = ref([])
  const pay_method = ref([])
  const opening_bank = ref('')
  const account = ref('')
  const account_name = ref('')
  const ids = ref([])
  const zhifu = ref('3')
  const jiesuan = ref('')
  const fileList = ref('')
  const xiaoji = ref(0)
  const zhifuOptions = ref([
      { label: '对公转账', value: '3' },
      { label: '现金', value: '2' },
      { label: '惠支付', value: '1' },
  ])
  const jiesuanOptions = ref([
    
  ])
  const showEdit = ref(false)
  const editColumn = ref([])
  const handleShouJu = (item)=>{
    shoujuShow.value = true
    shoujuItem.value = item
  }
  const isObjectEmpty = (obj)=>{   // 判断是否是空对象
    return Object.keys(obj).length === 0;
  }
  const handleZhifuInfos = (contract_id) =>{  // 获取支付公司的数据
    request({
      url: "system/userContract/remote",
      method: "post",
      data: {
        openPage: false,
        remoteOption:{
          filter: {id: ["=", contract_id]},
        }
      },
    }).then((res) => {
      let objarr = [
        { label: '预付款', value: '1',},
        { label: '周期结算', value: '2',disabled:true },
        { label: '现结', value: '3',disabled:true },
      ]
      console.log(pay_method.value)
      pay_method.value = res.data[0].pay_method.split(',')
      pay_method.value.map((v,i)=>{
        objarr.map((vv,ii)=>{
          if(v == vv.value){
            vv.disabled = false
          }
        })
      })
      let modelValues = '1'
      jiesuanOptions.value = objarr
      editColumn.value = [
        {
          dataIndex: 'price_config',
          componentName: "price_config_component",
          title: '',
          formType: 'component',
          component: shallowRef(PriceConfigEditCompanies)
        },
      ]
      showEdit.value = true
      res.data.map((v,i)=>{
          if(v.sign_dept_id == 7){
            getaccount(41)
          }
          if(v.sign_dept_id == 10){
            getaccount(42)
          }
        })
    });
  }
  const handleZhifu = ()=>{
    if(ids.value.length == 0){
      return Message.error('请选择需要支付的订单')
    }
    jiesuan.value = ''
    zhifu.value = '3'
    fileList.value = ''
    props.zhifuShow = true
  }
  const handlezhifuQuxiao = ()=>{
    emit("zhifushows",false)
  }
  const  spanMethodAll= ({record,rowIndex, columnIndex}) => {
      if (rowIndex === record.weizhi - record.weizhizong && columnIndex === 0) {
        return {rowspan: record.weizhizong,colspan:1}
      }
  };
  const handlePiLiang = (index) =>{  // 操作批量
    console.log(index)
    emit('chuanList',index)
  }
  const handleSOrt = (ceshiArr)=>{
    let arr = []           // 最终数据
    let linshiArr = []     //  未匹配的放数组里
    let linshititle = ''   // 临时变量
    ceshiArr.map((v,i)=>{
      if(i == 0){
        linshititle = v.name
        arr.push(v)
      }else{
        if(linshititle == v.name){
          arr.push(v)
        }else{
          linshiArr.push(v)
        }
      }
    })
    ceshiArr.map((v,i)=>{
      if(linshiArr.length != 0){
        linshiArr.map((vv,ii)=>{
          if(ii == 0){
            linshititle = linshiArr[0].name
            arr.push(linshiArr.shift())
          }else{
            if(linshititle == vv.name){
              arr.push(linshiArr.slice(ii,1))
            }
          }
          
        })
        
      }
    })
    arr.sort((a, b) => a.car_nos.localeCompare(b.car_nos));
    return arr
  }
  
  
  
  const handelzhifuOk = ()=>{ // 支付成功
    let obj = {}
    let ids = []
    let dept_id = ''
    console.log(props.list)
    props.list.map((v,i)=>{
      if(v.flag){
        ids.push(v.id)
        dept_id = v.dept_id
      }
    })
    if(jiesuan.value == 1 || jiesuan.value == 2){
      obj.pay_type = jiesuan.value == 1?'money':'periodic'
      obj.ids = ids.join(',')
    }
    if(jiesuan.value == 3){
      obj.pay_type = 'now_pay'
      obj.ids = ids.join(',')
      obj.now_pay_type = zhifu.value
      
      obj.transfer_proof_images = fileList.value
      obj.payment_method = zhifu.value
      obj.settlement_method = 1
      obj.notes = ''
      // obj.pay_order_id = this.zhifu_id    // 交易单号
      obj.dept_id = dept_id    // 公司
      obj.opening_bank = opening_bank.value    // 开户行
      obj.account = account.value    // 收款账户
      obj.account_name = account_name.value    // 开户行名称
    }
    request({
          url: "financial/payOrder/pay",
          method: "post",
          data: obj,
        }).then((res) => {
          jiesuan.value = ''
          zhifu.value = '3'
          fileList.value = ''
          emit("zhifushows",false)
          emit("shuaxin")
          Message.success(res.message);
        });
  }
  
  const setSelectedKeys = (val) => {
    ids.value = val;
  };
  const handleSelChange = (e)=>{
    let price = 0
    itemDetail.value.detail.map((v,i)=>{
      e.map((vv,ii)=>{
        if(vv == v.id){
          price += (v.pay_price - 0)
        }
      })
    })
    pay_price.value = price
  }
  const handleTuiHui = (item) =>{
    showModal.value = true
    selectedKeys.value = []
    pay_price_item.value = ''
    remark.value = ''
    ids.value = []
    fileList.value = []
    zhifu.value = '3'
    jiesuan.value = ''
    itemDetail.value = item
  }
  const handleQuxiao = ()=>{
    showModal.value = false
    pay_price.value = ''
  }
  const editShow = async (item) => {
    editRef.value.open(cloneDeep(item))
  }
  
  
  
  const refundSubmit = async (data) => {
    let submit = {
      id: data.predicateOrder.dept_id,
      event: "2",
      change_money: data.pay_price,
      change_money_type: "1",
      remark: data.remark,
      extend: {
        pay_price_item: data.pay_price_item,
        predicate_id: data.predicateOrder.id
      }
    }
    let res = await dept.addMoney({
      ...submit,
    })
    if (res.success) {
      Message.success(res.message)
      return true
    }
    return false
  }
  
  const editSubmit = async (formData) => {
    let submitData = cloneDeep(formData)
    
    submitData.pay_items_json.forEach(item => {
      item.pay_price = item.pay_price.toFixed(2)
    })
    if (!formData.id) {
      let res = await FinancialPayOrder.save(submitData)
      if (res.success) {
        Message.success(res.message)
        load(loadData)
        crudRef.value.refresh()
        return true
      }
      return false;
    }else{
      let res = await FinancialPayOrder.editPay(submitData, formData.id)
      if (res.success) {
        Message.success(res.message)
        load(loadData)
        crudRef.value.refresh()
        return true
      }
    }
    return false
  }
  const load = async (item) => {
    let res = await FinancialPayOrder.getList({
      prediction_order_id: item.id,
      pageSize: 1000,
    })
    let _data = res.data.items
    _data.map((v,i)=>{
      let arr = []
      let arrs = []
      v.detail.map((vv,ii)=>{
        if(vv.pay_price != '0.00'){
          arr.push(vv)
        }
      })
      for(let i = 0;i<arr.length;i++){
        let num = arrs.findIndex(item=>{
          return item.pay_name == arr[i].pay_name
        })
        if(num == -1){
          arrs.push(arr[i])
        }else{
          arrs[num].pay_price = ((arr[i].pay_price - 0) + (arrs[num].pay_price - 0)).toFixed(2)
        }
      }
      v.detail = arrs
    })
    
    
    data.value = _data
    visible.value = true
  }
  const getaccount = (type) =>{
    request({
          url: "system/dataDict/index",
          method: "get",
          params: {
            page:1,
                      pageSize:10,
                      type_id:type
          },
        }).then((res) => {
          opening_bank.value = res.data.items[0].value
                  account.value = res.data.items[1].value
                  account_name.value = res.data.items[2].value
        });
  }
  
  
  const tablecolumns = [
        {
          title: '收费项目',
          dataIndex: 'pay_name',
  
        },
        {
          title: '金额',
          dataIndex: 'pay_price',
        },
        {
          title: '计费公式',
          dataIndex: 'chi_price_role',
        },
  ];
  const columnsYg = reactive([
    {
      title: "收费项目",
          dataIndex: "item_name",
          align: "center",
          width:200,
          ellipsis:true,
          tooltip:true,
    },
    {
      title: "金额",
          dataIndex: "pay_price",
          align: "center",
          width:200,
          ellipsis:true,
          tooltip:true,
      slotName:'pay_price'
    },
    {
      title: "收费规则",
          dataIndex: "chi_price_role",
          align: "center",
          width:200,
          ellipsis:true,
          tooltip:true,
    },
  ])
  const tablecolumnsts = [
        {
          title: '车号',
          dataIndex: 'car_nos',
        },
        {
          title: '收费项目',
          dataIndex: 'pay_name',
  
        },
        {
            title: '不含税金额',
            dataIndex: 'no_tax_price',
        },
        {
            title: '税额',
            dataIndex: 'tax_price',
        },
        
        {
          title: '实际金额',
          dataIndex: 'pay_real_price',
        },
        {
          title: '备注',
          dataIndex: 'remark',
        },
  ];
  var loadData = {}
  defineExpose({
    open: async (item) => {
      console.log('item:',item)
      loadData = item
      crudRef.value.requestData()
      load(item)
    },
    handleZhifuInfo:async(item)=>{
      handleZhifuInfos(item)
    }
  })
  
  </script>
  
  <style lang="less" scoped>
  .flex{
      display:flex;
  }
  .flex_wrap{
      flex-wrap:wrap
  }
  
  .justify_between{
      justify-content:space-between
  }
  .justify_around{
      justify-content:space-around
  }
  .justify_center{
      justify-content:center
  }
  .align_center{
      align-items:center;
  }
  .flex_column{
    flex-direction: column;
  }
  .flex_1{
      flex:1
  }
  .width0{
      width:0
  }
  .ellipsis{
      overflow: hidden;
      text-overflow:ellipsis;
      white-space: nowrap;
  }
  .marbot14{
    margin-bottom:14px;
  }
  .marbot12{
    margin-bottom:12px;
  }
  .marbot8{
    margin-bottom:8px;
  }
  .marbot2{
    margin-bottom:2px;
  }
  .marr12{
    margin-right:12px;
  }
  .pad12{
    padding:12px;
  }
  .cursor{
    cursor: pointer;
  }
  .card{
    padding:20px;
    border-radius:8px;
    border:1px solid rgba(31, 108, 235, 1);
    background:rgba(242, 245, 255, 1);
    .butNt{
      font-size:12px;
      line-height:20px;
      border:1px solid rgba(31, 108, 235, 1);
      border-radius:3px;
      padding:2px 8px;
      color:rgba(31, 108, 235, 1);
    }
  }
  .cards{
    padding:20px;
    border-radius:8px;
    border:1px solid rgba(0, 0, 0, .15);
    margin-bottom:12px;
    width:100%;
    &:last-child{
      margin-bottom:0px;
    }
    .butNt{
      font-size:12px;
      line-height:20px;
      border:1px solid rgba(31, 108, 235, 1);
      border-radius:3px;
      padding:2px 8px;
      color:rgba(31, 108, 235, 1);
    }
  }
  </style>
  
